<template>
    <div class="member-edit">
        <el-form ref="formRef" :model="ruleForm" :rules="rules" label-width="94px">
            <el-form-item label="账号" prop="mobile" required>
                <el-input v-model="ruleForm.mobile" :disabled="isEdit"></el-input>
            </el-form-item>
            <el-form-item label="姓名" prop="userId" required>
                <el-select v-model="ruleForm.userId" placeholder="请输入姓名" :disabled="isEdit">
                    <el-option
                            v-for="item in userList"
                            :key="item.userId"
                            :label="item.name"
                            :value="item.userId"
                    >
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="开卡日期" required prop="openTime">
                <el-date-picker v-model="ruleForm.openTime" type="date" placeholder="年-月-日"
                                value-format="YYYY-MM-DD" :disabled="isEdit"></el-date-picker>
            </el-form-item>


            <el-form-item label="购卡类型" required prop="cardType">
                <el-select v-model="ruleForm.cardType" placeholder="请选择购卡类型" @change="()=>ruleForm.totalNum=''"
                           :disabled="isEdit">
                    <el-option v-for="item in cardTypes" :key="item.cardType" :value="item.cardType" :label="item.name">
                    </el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="有效期" required prop="totalNum" v-if="!rowData">
                <el-select v-model="ruleForm.totalNum" placeholder="请选择购卡类型">
                    <el-option v-for="day in validityDays" :key="day" :value="day"
                               :label="day+'天'">
                    </el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="截止日期" required prop="dueTime" v-else>
                <el-date-picker v-model="ruleForm.dueTime" type="date" placeholder="年-月-日"
                                value-format="YYYY-MM-DD"></el-date-picker>
            </el-form-item>

            <el-form-item label="剩余会员数" required prop="cardType">
                {{surplus.value}}
            </el-form-item>
        </el-form>
    </div>
</template>
<script lang="ts">
    import $ from '$';
    import {ref, Ref, computed} from 'vue'
    import {ElMessage} from 'element-plus'
    export default {
        props: {
            rowData: {
                type: Object,
                default: null
            },
            cardTypes: {
                type: Array,
                default: () => ([])
            },
            surplus: {},
            schoolId: {},
        },
        setup(props) {
            let formRef: Ref<any> = ref();
            let userList: any = ref([])  //姓名列表
            const validateMobile = async (rule, value, callback) => {
                let MobileReg = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
                if (!MobileReg.test(value)) {
                    callback(new Error('手机号码格式不正确！'))
                } else {
                    userList.value = []
                    let res: any = await $.http.get(`/system/student/queryStudentByMobile?mobile=${value}`);
                    // let res: any = await $.http.post(`/permission/user/queryAllByMobile?mobile=${value}`);
                    if (res.result) {
                        if (res.json?.length == 0) {
                            return callback(new Error('当前账号暂未注册！'))
                        } else {
                            userList.value = res.json;
                            return callback();
                        }
                    } else {
                        ElMessage.error(res.msg)
                        callback();
                    }
                }
            };
            const rules = ref({
                mobile: [
                    {required: true, message: '账号为必填项', trigger: 'blur'},
                    {validator: validateMobile, trigger: 'blur'}
                ],
                userId: [
                    {required: true, message: '姓名为必填项', trigger: 'blur'}
                ],
                openTime: [
                    {required: true, message: '开卡日期为必填项', trigger: 'blur'}
                ],
                cardType: [
                    {required: true, message: '购卡类型为必填项', trigger: 'change'}
                ],
                totalNum: [
                    {required: true, message: '有效期是必选项', trigger: 'change'}
                ],
                dueTime: [
                    {required: true, message: '截止日期是必选项', trigger: 'change'}
                ],
                //门店ID
                // storeId: [
                //     {required: true, message: '', trigger: 'blur',}
                // ],
            });
            const isEdit = ref(false);
            let ruleForm = ref({
                userId: '',
                userCode: '',
                userName: '',
                mobile: '',
                cardType: '',
                openTime: '',
                totalNum: '',
                dueTime: '',
            });

            if (props.rowData) {
                isEdit.value = true;
                let {id, userName, userCode, userId, cardType, mobile, openTime, dueTime} = props.rowData
                userList.value = [{id: id, name: userName, userCode, userId,}];
                ruleForm.value = {
                    ...ruleForm.value, userId, userCode, userName, mobile, dueTime, openTime
                    , cardType: cardType + ''
                }
            }

            let validityDays = computed(() =>
                props.cardTypes.find((bean) => bean.cardType == ruleForm.value.cardType)?.validityDays)

            const save = (resolve, reject) => {
                formRef.value.validate(async (valid) => {
                    if (valid) {
                        let userInfo: any = userList.value.find((bean: any) => bean.userId === ruleForm.value.userId)
                        let data: any = {
                            ...ruleForm.value,
                            storeId: props.schoolId,
                            userCode: userInfo?.userCode,
                            userName: userInfo?.name,
                        };
                        if (!props.rowData) {
                            delete data['dueTime']
                        }

                        let res = await $.http.post('/admin/memberCard/saveOrUpdate', data)
                        if (res.result) {
                            ElMessage.success('开卡成功!')
                        } else {
                            ElMessage.error('开卡失败!')
                        }
                        resolve(res)
                    } else {
                        reject();
                        return false
                    }
                })
            }
            return {ruleForm, rules, formRef, userList, save, validityDays, isEdit}
        }
    }
</script>
<style lang="scss" scoped>
    $mainWidth: 1120px;
    .member-edit {
        height: 100%;
        overflow: auto;
        overflow-x: hidden;

        :deep(.el-loading-mask) {
            border-radius: 20px;
        }

        :deep(.el-select ) {
            width: 100%;
        }

        :deep(.el-date-editor.el-input, .el-date-editor.el-input__inner) {
            width: 100%;
        }

        .btn-wrap {
            display: flex;
            justify-content: flex-end;
        }
    }
</style>
